package com.haifeng.lyw.blerobot.search;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.haifeng.lyw.blerobot.R;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by dell on 2017/8/29.
 */

public class DeviceListAdapter extends BaseAdapter{

    private List<DeviceBean> deviceList;
    private Context context;

    public DeviceListAdapter(List<DeviceBean> deviceList, Context context) {
        if (deviceList!=null){
            this.deviceList = deviceList;
        }else {
            this.deviceList = new ArrayList<>();
        }
        this.context = context;
    }

    @Override
    public int getCount() {
        return deviceList.size();
    }

    @Override
    public Object getItem(int i) {
        return deviceList.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    public void addDevice(DeviceBean deviceBean) {
       for (int i = 0;i<deviceList.size();i++){
           if (deviceList.get(i).getAddr().equals(deviceBean.getAddr())){
               return;
           }
       }
       deviceList.add(deviceBean);
        notifyDataSetChanged();
    }

    public DeviceBean getDevice(int postion){
        return deviceList.get(postion);
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        ViewHodler viewHodler;
        if (view == null){
            viewHodler = new ViewHodler();
            view = View.inflate(context, R.layout.search_listitem,null);
            viewHodler.deviceName = (TextView)view.findViewById(R.id.tv_deviceName);
            viewHodler.deviceAddress = (TextView)view.findViewById(R.id.tv_deviceAddr);
            viewHodler.rssi = (TextView)view.findViewById(R.id.tv_rssi);
            view.setTag(viewHodler);
        }else {
            viewHodler = (ViewHodler) view.getTag();
        }
        DeviceBean deviceBean = deviceList.get(i);
        viewHodler.deviceName.setText(deviceBean.getName());
        viewHodler.deviceAddress.setText(deviceBean.getAddr());
        viewHodler.rssi.setText(deviceBean.getRssi()+"");

        return view;
    }

    public void removeDevice(int i) {
        deviceList.remove(i);
        notifyDataSetInvalidated();
    }

    private class ViewHodler {
        TextView deviceAddress;
        TextView deviceName;
        TextView rssi;

    }

    public void clear(){
        deviceList.clear();
    }
}
